<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>递归-写一个函数实现n的阶乘</title>
</head>
<body>
<script>
    function mul(n) {
        var num = 1;
        for(var i=1; i<n+1; i++){
            num *= i;
        }
        return num;
    }
    console.log(mul(5));

    //使用递归
    //  n! = n * (n-1)!
    function mulnum(h) {
        if (h == 1) {
            return 1;
        }
        return h * mulnum(h-1);
    }

    console.log(mulnum(10));
    //分析：
    // mulnum(4) = 4 * mulnum(3);
    // mulnum(3) = 3 * mulnum(2);
    // mulnum(2) = 2 * mulnum(1);
    // mulnum(1)=1 --> mulnum(2)=2 -- mulnum(3)=6 mulnum(4)=24

    function fn(n){
        if(n ==1 || n == 2){
            return 1
        }
        return fn(n-1) + fn(n-2);
    }
    console.log(fn(20))
</script>
</body>
</html>
